//
//  HomeView.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import SwiftUI

struct HomeView: View {
    @EnvironmentObject var boxManager: BoxManager
    @State private var selectedActivities: Set<UUID> = []
    @State private var showBatchToolbar = false
    @State private var showWebView = false
    @State private var selectedActivity: Activity? = nil
    
    private let activities = Activity.allActivities
    
    var body: some View {
        NavigationView {
            ZStack {
                // 主要内容区域
                ScrollView {
                    LazyVGrid(columns: [GridItem(.flexible())], spacing: 16) {
                        ForEach(activities) { activity in
                            ActivityCard(activity: activity, 
                                       isSelected: selectedActivities.contains(activity.id),
                                       onSelect: { toggleSelection(activity) },
                                       onTap: { openActivity(activity) })
                        }
                    }
                    .padding()
                }
                .navigationTitle("DNF福利盒子")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        BoxSelector()
                    }
                    
                    ToolbarItem(placement: .navigationBarTrailing) {
                        if !selectedActivities.isEmpty {
                            Button("取消") {
                                selectedActivities.removeAll()
                                showBatchToolbar = false
                            }
                        }
                    }
                }
                
                // 批量操作工具栏
                if showBatchToolbar {
                    VStack {
                        Spacer()
                        BatchToolbar(selectedCount: selectedActivities.count) {
                            claimSelectedActivities()
                        } onCancel: {
                            selectedActivities.removeAll()
                            showBatchToolbar = false
                        }
                    }
                    .transition(.move(edge: .bottom))
                }
            }
        }
        .sheet(item: $selectedActivity) { activity in
            WebView(url: URL(string: activity.website)!, activity: activity)
        }
    }
    
    private func toggleSelection(_ activity: Activity) {
        if selectedActivities.contains(activity.id) {
            selectedActivities.remove(activity.id)
        } else {
            selectedActivities.insert(activity.id)
        }
        
        showBatchToolbar = !selectedActivities.isEmpty
    }
    
    private func openActivity(_ activity: Activity) {
        if selectedActivities.isEmpty {
            // 单个点击，直接打开
            selectedActivity = activity
        } else {
            // 批量选择模式，切换选择状态
            toggleSelection(activity)
        }
    }
    
    private func claimSelectedActivities() {
        // 实现批量领取逻辑
        print("开始批量领取选中的活动")
        // TODO: 实现批量领取功能
        
        // 清空选择
        selectedActivities.removeAll()
        showBatchToolbar = false
    }
}

// 盒子选择器组件
struct BoxSelector: View {
    @EnvironmentObject var boxManager: BoxManager
    
    var body: some View {
        Menu {
            ForEach(boxManager.getAllBoxes()) { box in
                Button(box.name) {
                    // 切换盒子
                    try? boxManager.switchToBox(boxId: box.id)
                }
            }
            
            Divider()
            
            NavigationLink(destination: BoxManagementView()) {
                Label("管理盒子", systemImage: "gearshape")
            }
        } label: {
            HStack {
                Image(systemName: "cube.fill")
                Text(boxManager.getCurrentBox().name)
                Image(systemName: "chevron.down")
            }
            .font(.subheadline)
            .foregroundColor(.blue)
        }
    }
}

// 活动卡片组件
struct ActivityCard: View {
    let activity: Activity
    let isSelected: Bool
    let onSelect: () -> Void
    let onTap: () -> Void
    
    var body: some View {
        ZStack(alignment: .topTrailing) {
            // 主卡片内容
            Button(action: onTap) {
                VStack(spacing: 0) {
                    // 活动图片
                    AsyncImage(url: URL(string: activity.imageUrl)) { image in
                        image
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                    } placeholder: {
                        Color.gray.opacity(0.3)
                    }
                    .frame(height: 180)
                    .clipped()
                    
                    // 活动信息
                    VStack(alignment: .leading, spacing: 8) {
                        Text(activity.name)
                            .font(.headline)
                            .foregroundColor(.primary)
                        
                        Text(activity.dateRangeString)
                            .font(.caption)
                            .foregroundColor(.secondary)
                        
                        if activity.daysRemaining > 0 {
                            Text("剩余 \(activity.daysRemaining) 天")
                                .font(.caption)
                                .foregroundColor(.orange)
                        }
                    }
                    .padding()
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .background(Color.white)
                }
            }
            .background(Color.white)
            .cornerRadius(16)
            .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 2)
            .overlay(
                RoundedRectangle(cornerRadius: 16)
                    .stroke(isSelected ? Color.blue : Color.clear, lineWidth: 2)
            )
            
            // 选择复选框
            if isSelected {
                Image(systemName: "checkmark.circle.fill")
                    .font(.title2)
                    .foregroundColor(.blue)
                    .padding(8)
                    .background(Color.white)
                    .clipShape(Circle())
                    .shadow(radius: 2)
                    .padding(8)
            }
        }
    }
}

// 批量操作工具栏
struct BatchToolbar: View {
    let selectedCount: Int
    let onClaim: () -> Void
    let onCancel: () -> Void
    
    var body: some View {
        HStack {
            Text("已选择 \(selectedCount) 个活动")
                .font(.subheadline)
                .foregroundColor(.secondary)
            
            Spacer()
            
            Button("取消", action: onCancel)
                .foregroundColor(.secondary)
            
            Button("一键领取", action: onClaim)
                .padding(.horizontal, 16)
                .padding(.vertical, 8)
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(20)
        }
        .padding()
        .background(Color.white)
        .cornerRadius(16)
        .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: -2)
        .padding(.horizontal)
        .padding(.bottom, 8)
    }
}

#Preview {
    HomeView()
        .environmentObject(BoxManager.shared)
}